<?php


namespace app\common\model;


use plug\SUtil;
use think\Db;

class ApplyReg extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_applyreg';
    // 主键ID
    protected $pk = 'applyreg_id';

    //新增、编辑(后台操作)
    function edit($params, $id=0,$ischeck = false){
        if($id>0){
            // 更新条件
            $where = ["{$this->pk}" => $id];
            if($ischeck == true){
                $this->startTrans();
            }
            $rs = $this->allowField(true)->save($params, $where);
        }else{
            $params['add_time'] = time();
            $params['apply_ip'] = SUtil::getIp();
            $params['pass_random'] = SUtil::random(6,0);
            $params['user_pass'] = SUtil::getHashBackend($params['user_pass'], $params['pass_random']);
            // 更新数据
            $this->allowField(true)->save($params);
            $rs = $this->pk;
        }
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            return false;
        }
        if($ischeck == true){
            $result = $this->addadminandshop($id);
            if($result === false){
                $this->rollback();
                return false;
            }
            $this->commit();
        }
        return $rs;
    }


    // 查询列表
    function get_list($cond, $orderby, $item, $limit)
    {
        // 条件
        $where = null;
        if(!empty($cond['user_name'])){
            $where[] = ['a.user_name','like',"%".$cond['user_name']."%"];
        }

        if(!empty($cond['group_id'])){
            $where[] = ['a.group_id','=',$cond['group_id']];
        }

        $rs = Db::table($this->table)
            ->alias('a')
            ->leftJoin('ddt_group b','a.group_id = b.group_id')
            ->where($where)
            ->field($item)
            ->order($orderby)
            ->paginate($limit);
        return $rs;
    }

    // 处理添加管理用户和商铺
    public function addadminandshop($applyid)
    {
        $data = $this->where("{$this->pk}",'=',$applyid)->find()->toArray();
        switch(true){
            case $data['apply_type'] == 1:
                $groupid = 9;
                $shop_type = 1;
                break;
            case $data['apply_type'] == 2:
                $groupid = 10;
                $shop_type = 2;
                break;
            default:
                $groupid = 11;
                $shop_type = 3;
                break;
        }
        $shopModel = new Shops();
//        $shop = $shopModel->where('shopphone','=',$data['telphone'])->find();
        $shop = $shopModel->getOne(array('shop_phone'=>$data['telphone']),'*');
        if(!empty($shop)){
            $this->setError(-1,'已存在该手机号注册商家');
            return false;
        }
//        var_dump($data);die;
        $areaModel = new Area();
        $areacond['areas'] = [$data['province_code'],$data['city_code'],$data['area_code']];
        $areas = $areaModel->get_list($areacond,'*')->toArray();
        $data['province'] = '省';
        $data['city'] = '市';
        $data['area'] = '区';
        if(!empty($areas)){
            $areas = array_column($areas,'name','level');
            isset($areas[1])?$data['province'] = $areas[1]:'';
            isset($areas[2])?$data['city'] = $areas[2]:'';
            isset($areas[3])?$data['area'] = $areas[3]:'';
        }
//        var_dump($areas);die;

        // 插入商铺
        $shopparams = [
            'shop_name' => $data['shopname'],
            'shop_phone' => $data['telphone'],
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'licenseimg' => $data['licenseimg'],
            'imagesurl' => $data['imagesurl'],
            'shop_manager' => $data['shop_manager'],
            'lon' => $data['lon'],
            'lat' => $data['lat'],
            'shop_type' => $shop_type,
            'remark' => $data['remark'],
            'add_time' => time(),
            'profit' => $data['profit'],
        ];
        $userModel = new User();
        $userinfo = $userModel->getOne([['user_id','=',$data['user_id']]]);
        $shopparams['sale_id'] = $userinfo['invite_uid'];
        if(!empty($data['salecode']) && !empty($userinfo['invite_uid'])){
            $inviteuser = $userModel->getOne([['sales_code','=',$data['salecode']]]);
            $inviteuser = $inviteuser->toArray();
            $shopparams['sale_id'] = $inviteuser['user_id'];
        }
        $result1 = $shopModel->edit($shopparams);
        if($result1 === false){
            $this->setError("-1",$shopModel->getError());
            return false;
        }
        $shopid = $result1;

        $adminModel = new Admin();
        $admin = $adminModel->where('phone','=',$data['telphone'])->find();
        if(!empty($admin)){
            $this->setError(-1,'已存在该管理员账号');
            return false;
        }
        // 插入管理员
        $adminparams = [
            'user_name' => $data['telphone'],
            'phone' => $data['telphone'],
            'real_name' => $data['shop_manager'],
            'user_pass' => $data['user_pass'],
            'pass_random' => $data['pass_random'],
            'group_id' => $groupid,
            'shop_id' => $shopid,
            'add_time' => time(),
        ];

        $result2 = $adminModel->edit($adminparams);
        if($result2 === false){
            $this->setError("-1",$adminModel->getError());
            return false;
        }
        return true;
    }


    /**
     * 更新用户登录成功的信息
     */
    public function update_login($userid,$user_pass=''){
        $adminModel = new Admin();

        if(empty($userid)){
            return false;
        }
        $where = ['user_id' => $userid];

        $loginSucInfo = array(
            'last_time'=>time(),
            'last_ip'=>SUtil::getIp()
        );
        if($user_pass){
            $loginSucInfo['pass_random'] = SUtil::random(6,0);
            $loginSucInfo['user_pass'] = SUtil::getHashBackend($user_pass, $loginSucInfo['pass_random']);
        }
        $re = $adminModel->getUpdate($where, $loginSucInfo);
        if($re==false||!$loginSucInfo['pass_random']){//未更新成功或者未更新pass_random那么返回原来的sn
            $one = $adminModel->getOne($where,'pass_random');
            $loginSucInfo['pass_random'] = $one['pass_random'];
        }
        return $loginSucInfo['pass_random'];
    }




}